//
//  KVNDataStoreEngine.m
//  Test1
//
//  Created by KelvinYeung on 15/7/27.
//  Copyright (c) 2015年 KelvinYeung. All rights reserved.
//

#import "KVNDataStoreEngine.h"




@interface KVNDataStoreEngine()
@property NSArray  *pathComponents;
@end

@implementation KVNDataStoreEngine

@synthesize managedObjectContext;
@synthesize pathComponents;

- (instancetype)init{
    self = [super init];
    [self initCoreData];
    return self;
    
}




#pragma mark - CoreData
- (void) initCoreData{
    
    pathComponents = @[@"homeNews.data"];
    
    
    //从应用程序包加载模型文件
    NSManagedObjectModel * model = [NSManagedObjectModel mergedModelFromBundles:nil];
    
    //传入模型对象，初始化PersistentStoreCoordinator
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    //构特Sqlite数据文件的路径
    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
   
    for(NSString *pathComponent in pathComponents){
        NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:pathComponent]];
        //添加持久化存储库，这里使用Sqlite为存储库
        NSError *error = nil ;
        NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
        
        if (store == nil) {
            [NSException raise:@"添加数据库错误" format:@"%@",[error localizedDescription]];
        }

    }
   
    
    
    // 初始化上下文，设置persistentStoreCoordinator
    managedObjectContext = [[NSManagedObjectContext alloc] init];
    managedObjectContext.persistentStoreCoordinator = psc;
    
    
}



/**
 *  更新数据
 *  参数：
 **/

- (void) updateDataForName:(NSString *) entityName object:(NSMutableDictionary *) object{
    //传入上下文，创建一个homeNews实体对象
    NSManagedObject *homeNews = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:managedObjectContext];
    
    //设置HomeNews的简单属性
    [homeNews setValuesForKeysWithDictionary:object];
    
    //利用上下文，将数据同步到持入化存储库
    NSError *error = nil;
    BOOL success = [managedObjectContext save:&error];
    if(!success) {
        [NSException raise:@"访问数据库错误" format:@"%@",[error localizedDescription]];
    }
    
}


- (NSArray *) queryWithEntityName:(NSString *) entityName sortDescriptor:(NSString *) sortDescriptor{
    
    //初始一个查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //设置要查询的实体
    request.entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    
    //设置排序
    if(sortDescriptor != nil){
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:sortDescriptor ascending:YES];
        request.sortDescriptors = [NSArray arrayWithObjects:sort, nil];
    }
    
    //设置条件过滤 ,SQL中的%用*代替
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title LIKE %@",@"*hello*"];
    //    request.predicate = predicate;
    
    
    //执行请求
    NSError *error = nil;
    NSArray *objs = [managedObjectContext executeFetchRequest:request error:&error];
    if (error){
        [NSException raise:@"查询错误" format:@"%@" ,[error localizedDescription]];
    }
    
    return objs;
    
    
}

- (void) deleteObject:(NSManagedObject *)object{
    
    //传入要删除的实体对象
    [managedObjectContext deleteObject:object];
    //将结果同步到数据库
    NSError *error = nil;
    if(error){
        [NSException raise:@"删除错误" format:@"%@",[error localizedDescription]];
    }
    
}

@end
